package com.dfbz.service.impl;

import com.dfbz.dao.DeptDao;
import com.dfbz.model.Dept;
import com.dfbz.service.DeptService;

import java.util.*;

public class DeptServiceImpl implements DeptService {

    private DeptDao deptDao = new DeptDao();


    @Override
    public List<Dept> getAll() {
        return deptDao.findAll();
    }


    @Override
    public List<Map<String, Object>> getDeptList() {
        //数据库查出所有数据（元数据）
        List<Map<String, Object>> all = deptDao.findUserList();

        //定义一个不能重复的部门ID集合
        Set<String> ids = new HashSet<>();

        //部门列表数据返回出去
        List<Map<String, Object>> deptList = new ArrayList<>();
        Map<String,Object> deptMap;

        for (Map<String,Object> map : all){
            String deptId = map.get("deptId").toString();
            if (!ids.contains(deptId)){
                deptMap = new HashMap<>();
                deptMap.put("deptId",deptId);
                deptMap.put("deptName",map.get("dept_name"));
                deptMap.put("deptCount",1);
                deptList.add(deptMap);
            }else {
                for (Map<String,Object>dept : deptList){
                    if (deptId.equals(dept.get("deptId").toString())){
                        int count = Integer.parseInt(dept.get("deptCount").toString());
                        dept.put("deptCount",++count);
                        break;
                    }
                }
            }
            ids.add(deptId);
        }
        //
        List<Map<String, Object>> userList;
        Map<String,Object> userMap;

        for (Map<String,Object> dept : deptList) {
            String dId = dept.get("deptId").toString();
            userList = new ArrayList<>();

            for (Map<String, Object> map : all) {
                String deptId = dept.get("dept_id").toString();
                if (deptId.equals(dId)) {
                    userMap = new HashMap<>();
                    userMap.put("deptId", map.get("dept_id"));
                    userMap.put("deptName", map.get("dept_name"));
                    userList.add(userMap);
                }
            }
            dept.put("userList",userList);
        }
        return deptList;
    }

}
